/**
*@author Juan Bessonart @ 06/02/2008 [re-factory by Nicolas Gunther 13-02-2009]
*/
public with sharing class DiscussionWidgetMostReadController {
	
	private List<DiscussionTopic__c> mostRead;
	
	/**
	* Constructor
	*/
	public DiscussionWidgetMostReadController() {
		mostRead = new List<DiscussionTopic__c>();
		reloadMostRead();
	}
	
	/**
	* Reload the Most Readed Discussions in mostRead
	*/
	public void reloadMostRead() {
		mostRead.clear();
		List<DiscussionMember__c> myMemberships = new List<DiscussionMember__c>();
		List<DiscussionForum__c> myForums = new List<DiscussionForum__c>(); 
		myMemberships = [select d.DiscussionForum__r.Id, d.DiscussionForum__c from 
							DiscussionMember__c d where d.User__c =: UserInfo.getUserId() and d.DiscussionForum__r.Type__c = 'private'];
		
		for(DiscussionMember__c member : myMemberships)
			myForums.add(member.DiscussionForum__r);
		
		List<DiscussionTopic__c> mostReadAux  = new List<DiscussionTopic__c>();	
		mostReadAux = [select Id, Subject__c, ViewCount__c
					from DiscussionTopic__c where DiscussionForum__r.Type__c != 'private' or DiscussionForum__c in:myForums
					order by ViewCount__c desc nulls last limit 5];
		
		for( DiscussionTopic__c o : mostReadAux )
		{
			if( o.Subject__c.length() > 30 ){
				o.Subject__c = o.Subject__c.substring( 0, 20 ) + '...';
				mostRead.add( o ); 
			}
			else{
				mostRead.add( o ); 
			}		
		}
	}
	
	/**
	* Get more readed topics
	*@return List<DiscussionTopic__c>
	*/
	public List<DiscussionTopic__c> getMostRead () {
		reloadMostRead();
		return mostRead;
	}

	/**
	* Get the size of mostRead
	* @return Integer
	*/
	public Integer getMostReadSize() {
		return mostRead.size();
	}
}